import {memo, useEffect, useRef, useState} from "react";
import {SliderContainer} from "./styled";
import {throttle,} from '@/utils'
import {getDeviceType} from "./utils"

/**
 * 鼠标按下的时候，开启document的mouseover监听，记录开始位置
 * document的mouseover监听（持续改变thumb的位置！）
 * 鼠标up的时候，关闭document的mouseover的监听，记录结束为止
 */
export default memo(function Slider(props) {
    console.log("Slice Rendered")
    const {percent, onChange, ...rest} = props;

    let statRef = useRef('normal')//ondrag 判断状态，如果当前状态为ondrag则不让执行自然绘制！
    let move, down, up;
    let _percent = 0
    if (getDeviceType() === 3) {
        move = 'mousemove';
        down = "mousedown";
        up = "mouseup"
    } else {
        move = 'touchmove';
        down = "touchstart";
        up = "touchend"
    }
    const trackRef = useRef()
    const thumbRef = useRef()
    const thumbRefMouseDownHandler = (e) => {
        console.log("摁下")
        document.addEventListener(move, domMousemoveHandler, true)
        document.addEventListener(up, thumbRefMouseupHandler, true)
        statRef.current = "ondrag"
    }
    const thumbRefMouseupHandler = (e) => {
        console.log('抬手')
        document.removeEventListener(move, domMousemoveHandler, true)
        document.removeEventListener(up, thumbRefMouseupHandler, true)
        statRef.current = "normal"
        onChange(_percent)
    }

    // document mouseover事件，持续改变thumb的 left值（节流）
    const domMousemoveHandler = throttle((e) => {
        if (e.pageX || e.pageX === 0) {
            doChangeRangeHandler(e.pageX)
        } else {
            doChangeRangeHandler(e.targetTouches[0].screenX)
        }
    }, 20)
    const trackRefClickHandler = (e) => {
        doChangeRangeHandler(e.pageX)
        onChange(_percent)
    }
    const doChangeRangeHandler = (mouseXPositionOnPage) => {
        /*
            轨道可以滑动的最长距离：
            轨道长度+轨道距离左侧的长度！
        */
        _percent = 100 * (mouseXPositionOnPage - trackRef.current.offsetLeft) / trackRef.current.offsetWidth
        //边界处理
        if (_percent <= 0) {
            _percent = 0
        } else if (_percent >= 100) {
            _percent = 100
        }
        doDrawRange(_percent)
    }
    const doDrawRange = (percent) => {
        thumbRef.current.style.left = percent + "%"
        trackRef.current.style.backgroundImage = `linear-gradient(90deg, #f00,#FFF ${percent}%, #FFF)`
    }
    useEffect(() => {
        statRef.current === "normal" && doDrawRange(percent)
    }, [percent])
    useEffect(() => {
        console.log("event bind")
        thumbRef.current.addEventListener(down, thumbRefMouseDownHandler, true)
        trackRef.current.addEventListener('click', trackRefClickHandler, true)
        return () => {
            thumbRef.current.removeEventListener(down, thumbRefMouseDownHandler, true)
            document.removeEventListener(up, thumbRefMouseupHandler, true)
            trackRef.current.removeEventListener('click', trackRefClickHandler, true)
        }
    }, [])

    return <SliderContainer ref={trackRef} {...rest}>
        <span className='thumb' ref={thumbRef}></span>
    </SliderContainer>
})